package net.zjitc.yaobei_backed.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.zjitc.yaobei_backed.dto.ApiResponse;
import net.zjitc.yaobei_backed.dto.StudyStats;
import net.zjitc.yaobei_backed.dto.quiz.QuizCheckRequest;
import net.zjitc.yaobei_backed.dto.quiz.QuizCheckResponse;
import net.zjitc.yaobei_backed.dto.quiz.QuizOption;
import net.zjitc.yaobei_backed.dto.quiz.QuizQuestion;
import net.zjitc.yaobei_backed.dto.study.StudyResultRequest;
import net.zjitc.yaobei_backed.dto.study.StudyResultResponse;
import net.zjitc.yaobei_backed.entity.User;
import net.zjitc.yaobei_backed.entity.Word;
import net.zjitc.yaobei_backed.repository.UserRepository;
import net.zjitc.yaobei_backed.repository.WordRepository;
import net.zjitc.yaobei_backed.service.StudyService;
import net.zjitc.yaobei_backed.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 学习统计控制器
 */
@RestController
@RequestMapping("/api/study")
@CrossOrigin
public class StudyController {

    @Autowired
    private StudyService studyService;

    @Autowired
    private WordService wordService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private WordRepository wordRepository;

    /**
     * 获取当前用户的学习统计
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<StudyStats>> getStats() {
        // 从Security上下文获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 根据username查询用户获取userId
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userRepository.selectOne(queryWrapper);
        
        if (user == null) {
            return ResponseEntity.ok(ApiResponse.error(404, "用户不存在"));
        }
        
        StudyStats stats = studyService.getStudyStats(user.getId());
        return ResponseEntity.ok(ApiResponse.success(stats));
    }

    /**
     * 获取今天需要复习的单词列表
     * @param limit 返回数量限制（默认10，最大50）
     * @return 单词列表
     */
    @GetMapping("/review-words")
    public ResponseEntity<ApiResponse<List<Word>>> getReviewWords(
            @RequestParam(defaultValue = "10") Integer limit) {
        // 限制数量范围
        if (limit <= 0 || limit > 50) {
            limit = 10;
        }

        // 从Security上下文获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 根据username查询用户获取userId
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userRepository.selectOne(queryWrapper);
        
        if (user == null) {
            return ResponseEntity.ok(ApiResponse.error(404, "用户不存在"));
        }
        
        List<Word> words = wordService.getTodayReviewWords(user.getId(), limit);
        return ResponseEntity.ok(ApiResponse.success(words));
    }

    /**
     * 获取需要学习的新单词列表（未学习过的单词）
     * @param limit 返回数量限制（默认10，最大50）
     * @return 单词列表
     */
    @GetMapping("/new-words")
    public ResponseEntity<ApiResponse<List<Word>>> getNewWords(
            @RequestParam(defaultValue = "10") Integer limit) {
        // 限制数量范围
        if (limit <= 0 || limit > 50) {
            limit = 10;
        }

        // 从Security上下文获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 根据username查询用户获取userId
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userRepository.selectOne(queryWrapper);
        
        if (user == null) {
            return ResponseEntity.ok(ApiResponse.error(404, "用户不存在"));
        }
        
        List<Word> words = wordService.getNewWordsToLearn(user.getId(), limit);
        return ResponseEntity.ok(ApiResponse.success(words));
    }

    /**
     * 生成学习题目（新单词）
     */
    @GetMapping("/quiz/new")
    public ResponseEntity<ApiResponse<List<QuizQuestion>>> getNewQuiz(
            @RequestParam(defaultValue = "10") Integer limit) {
        if (limit <= 0 || limit > 50) {
            limit = 10;
        }
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.error(401, "未登录"));
        }
        List<Word> words = wordService.getNewWordsToLearn(userId, limit);
        return ResponseEntity.ok(ApiResponse.success(buildQuiz(words)));
    }

    /**
     * 生成复习题目（今日需要复习的）
     * 兼容两种路径：/api/study/review 和 /api/study/quiz/review
     */
    @GetMapping({"/review", "/quiz/review"})
    public ResponseEntity<ApiResponse<List<QuizQuestion>>> getReviewQuiz(
            @RequestParam(defaultValue = "10") Integer limit) {
        if (limit <= 0 || limit > 50) {
            limit = 10;
        }
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.error(401, "未登录"));
        }
        List<Word> words = wordService.getTodayReviewWords(userId, limit);
        return ResponseEntity.ok(ApiResponse.success(buildQuiz(words)));
    }

    /**
     * 检查答题结果并自动保存学习记录
     * 根据答题结果自动计算熟练度
     */
    @PostMapping("/quiz/check")
    public ResponseEntity<ApiResponse<QuizCheckResponse>> checkAnswer(
            @RequestBody QuizCheckRequest request,
            @RequestParam(required = false, defaultValue = "learn") String mode) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.error(401, "未登录"));
        }
        
        // 1. 查询单词信息
        Word word = wordRepository.selectById(request.getWordId());
        if (word == null) {
            return ResponseEntity.ok(ApiResponse.error(404, "单词不存在"));
        }
        
        // 2. 查找正确答案
        // 重新生成题目以获取正确答案的选项ID（因为选项是随机打乱的）
        // 注意：实际生产环境中，建议在题目数据中保存正确答案的选项ID，避免重复生成
        QuizQuestion question = buildQuiz(List.of(word)).get(0);
        String correctOptionId = question.getCorrectOptionId();
        String correctText = word.getMeaning();
        
        // 3. 判断答题是否正确（通过选项ID比较）
        boolean isCorrect = correctOptionId != null && correctOptionId.equals(request.getSelectedOptionId());
        
        // 如果选项ID匹配失败，尝试通过文本匹配（容错处理）
        if (!isCorrect && request.getSelectedOptionText() != null) {
            isCorrect = correctText.equals(request.getSelectedOptionText());
        }
        
        // 4. 根据答题结果自动计算熟练度
        String confidence;
        Float recallConfidence;
        
        if (isCorrect) {
            // 答对了：根据答题速度或难度可以进一步细分，这里简化为"know"
            confidence = "know";
            recallConfidence = 0.9f; // 答对了，置信度较高
        } else {
            // 答错了：需要复习
            confidence = "forget";
            recallConfidence = 0.2f; // 答错了，置信度较低
        }
        
        // 5. 保存学习记录
        StudyResultRequest studyRequest = new StudyResultRequest();
        studyRequest.setWordId(request.getWordId());
        studyRequest.setMode(mode); // "learn" 或 "review"
        studyRequest.setConfidence(confidence);
        studyRequest.setRecallConfidence(recallConfidence);
        
        StudyResultResponse studyRecord = studyService.saveStudyResult(userId, studyRequest);
        
        // 6. 构建返回结果
        QuizCheckResponse response = new QuizCheckResponse();
        response.setCorrect(isCorrect);
        response.setCorrectOptionId(correctOptionId);
        response.setCorrectText(correctText);
        response.setMeaning(word.getMeaning());
        response.setPhonetic(word.getPhonetic());
        response.setExampleSentenceCn(word.getExampleSentenceCn());
        response.setExampleSentenceEn(word.getExampleSentenceEn());
        response.setAudioUrl(word.getAudioUrl());
        response.setStudyRecord(studyRecord); // 包含学习记录信息
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }

    /**
     * 保存学习/复习结果（手动指定熟练度）
     * 用于用户手动评估记忆程度的情况
     */
    @PostMapping("/result")
    public ResponseEntity<ApiResponse<StudyResultResponse>> saveStudyResult(
            @RequestBody StudyResultRequest request) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.error(401, "未登录"));
        }
        StudyResultResponse response = studyService.saveStudyResult(userId, request);
        return ResponseEntity.ok(ApiResponse.success(response));
    }


    // -------- helper --------
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", username);
        User user = userRepository.selectOne(qw);
        return user == null ? null : user.getId();
    }

    /**
     * 为单词生成4个选项（1个正确答案 + 3个错误答案，已打乱）
     */
    private List<QuizOption> generateOptionsForWord(Word word) {
        // 选出 3 个错误释义（从其他单词随机抽取）
        QueryWrapper<Word> otherQ = new QueryWrapper<>();
        otherQ.ne("id", word.getId());
        otherQ.select("id", "word", "meaning"); // 同时查询word和meaning
        otherQ.last("ORDER BY RAND() LIMIT 3");
        List<Word> distractors = wordRepository.selectList(otherQ);

        List<QuizOption> options = new ArrayList<>();
        // 添加正确答案（包含单词和意思）
        options.add(new QuizOption(
            UUID.randomUUID().toString(), 
            word.getMeaning(), 
            word.getWord()
        ));
        // 添加3个错误答案（包含单词和意思）
        for (Word d : distractors) {
            if (d.getMeaning() != null && !d.getMeaning().trim().isEmpty()) {
                options.add(new QuizOption(
                    UUID.randomUUID().toString(), 
                    d.getMeaning(), 
                    d.getWord() != null ? d.getWord() : ""
                ));
            }
        }
        // 如果错误答案不够3个，用空字符串填充（理论上不应该发生）
        while (options.size() < 4) {
            options.add(new QuizOption(
                UUID.randomUUID().toString(), 
                "选项" + options.size(), 
                ""
            ));
        }
        // 打乱顺序
        Collections.shuffle(options);
        return options;
    }

    /**
     * 构建题目列表
     */
    private List<QuizQuestion> buildQuiz(List<Word> words) {
        List<QuizQuestion> list = new ArrayList<>();
        for (Word w : words) {
            List<QuizOption> options = generateOptionsForWord(w);
            QuizQuestion question = new QuizQuestion();
            question.setWordId(w.getId());
            question.setWord(w.getWord());
            question.setPhonetic(w.getPhonetic());
            question.setAudioUrl(w.getAudioUrl());
            question.setOptions(options);
            question.setCorrectMeaning(w.getMeaning()); // 正确答案（用于前端校验）
            
            // 找到正确答案的选项ID
            String correctOptionId = null;
            for (QuizOption option : options) {
                if (option.getText().equals(w.getMeaning())) {
                    correctOptionId = option.getId();
                    break;
                }
            }
            question.setCorrectOptionId(correctOptionId); // 正确答案的选项ID
            
            question.setExampleSentenceCn(w.getExampleSentenceCn()); // 中文例句
            question.setExampleSentenceEn(w.getExampleSentenceEn()); // 英文例句
            list.add(question);
        }
        return list;
    }
}

